package com.codeboy.webshell.WebSocket.interceptor;

import com.codeboy.webshell.WebSocket.constant.ConstantPool;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
import java.util.UUID;

/**
 * @Description : WebSSH拦截器
 * @Author : 崔昌赫
 * @Date : 2021/9/12
 */
public class WebSocketInterceptor implements HandshakeInterceptor {

    /**
     * @Description :处理器处理前调用
     * @param serverHttpRequest 服务器回传的rq
     * @param serverHttpResponse 服务器回传的rp
     * @param webSocketHandler 处理器实例
     * @param map 信息存储
     * @return 是否处理成功
     * @throws Exception 处理失败后抛出错误
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        if(serverHttpRequest instanceof ServletServerHttpRequest){
            ServletServerHttpRequest request =(ServletServerHttpRequest) serverHttpRequest;
            //生成一个随机UUID
            String uuid = UUID.randomUUID().toString().replace("-","");
            //将uuid放到websocketsession中
            map.put(ConstantPool.USER_UUID_KEY,uuid);
            return true;
        }else{
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}

